import Form, {FormComponentProps} from 'antd/lib/form';
import {Dispatch} from 'redux';
import React, {Component, Fragment} from 'react';
import {TableListItem, TableListPagination} from '@/data';
import StandardTable, {StandardColumnProps} from '@/components/StandardTable';
import {IStateType} from './model';
import {PageHeaderWrapper} from '@ant-design/pro-layout';
import {connect} from 'dva';
import {Button, Card, Col, Divider, Icon, Input, Popconfirm, Row, Tag} from 'antd';
import styles from './index.less';
import {SorterResult} from 'antd/lib/table';
import AddView from "./components/AddView";
import EditView from "./components/EditView";

const FormItem = Form.Item;

interface TableListProps extends FormComponentProps {
  BLOCK_NAME_CAMEL_CASE: IStateType;
  dispatch: Dispatch<any>;
  loading: boolean;
}

interface TableListState {
  selectedRows: Array<TableListItem>;
  formValues: { [key: string]: string };
  stepFormValues: Partial<TableListItem>;
  selectedRecord: any;
  addVisible: boolean;
  editVisible: boolean
}

const SEX = {
  true: {color: 'blue', text: '侠客'},
  false: {color: 'red', text: '女侠'},
  UNKNOWN: {color: 'red', text: '其他'},
};

const POS_LEVEL = {
  P5: {color: 'red', text: '员工'},
  P6: {color: 'magenta', text: '高级'},
  P7: {color: 'green', text: '架构'},
  P8: {color: 'blue', text: '主任'},
  UNKNOWN: {color: 'red', text: '其他'},
};

@connect(({BLOCK_NAME_CAMEL_CASE, loading}: { BLOCK_NAME_CAMEL_CASE: IStateType; loading: {models: {[key: string]: boolean;}} }) => ({BLOCK_NAME_CAMEL_CASE, loading: loading.models.BLOCK_NAME_CAMEL_CASE}))
class TableList extends Component<TableListProps, TableListState> {
  state: TableListState = {
    selectedRows: [],
    formValues: {},
    stepFormValues: {},
    selectedRecord: null,
    addVisible: false,
    editVisible:false
  };

  columns: StandardColumnProps[] = [
    {
      title: '姓名',
      dataIndex: 'name',
      align: 'center',
    },
    {
      title: '年龄',
      width: '100px',
      dataIndex: 'age',
      align: 'center',
    },
    {
      title: '性别',
      dataIndex: 'sex',
      width: '120px',
      align: 'center',
      render(val: any) {
        const {color, text} = SEX[val] || SEX.UNKNOWN;
        return <Tag color={color}>{text}</Tag>;
      },
    },
    {
      title: '工号',
      align: 'center',
      dataIndex: 'workNum',
    },
    {
      title: '职级',
      align: 'center',
      dataIndex: 'level',
      render(val: any) {
        const {color, text} = POS_LEVEL[val] || POS_LEVEL.UNKNOWN;
        return <Tag color={color}>{text}</Tag>;
      },
    },
    {
      title: '手机号',
      align: 'center',
      dataIndex: 'phone',
    },
    {
      title: '身份证',
      align: 'center',
      dataIndex: 'idCard',
    },
    {
      title: '备注',
      align: 'center',
      dataIndex: 'description',
      ellipsis: true,
    },
    {
      title: '操作',
      align: 'center',
      width: '120px',
      render: (text, record) => (
        <Fragment>
          <a onClick={() => this.handleUpdateModalVisible(true, record)}>编辑</a>
          <Divider type="vertical"/>
          <Popconfirm title="确认要删除该条数据吗？" onConfirm={() => this.handleRemove(record)}>
            <a href="#">删除</a>
          </Popconfirm>
        </Fragment>
      ),
    },
  ];

  componentDidMount() {
    const {dispatch} = this.props;
    dispatch({type: 'BLOCK_NAME_CAMEL_CASE/fetch'});
  }

  handleAdd = (data: any, callback: () => void) => {
    const {dispatch} = this.props;
    dispatch({type: 'BLOCK_NAME_CAMEL_CASE/add', payload: {data, callback}});
  };

  handleUpdateModalVisible = (flag?: boolean, record?: any) => {
    this.setState({ editVisible: !!flag, selectedRecord: record });
  };

  handleEdit = (data: any, callback: () => void) => {
    const {dispatch} = this.props;
    dispatch({type: 'BLOCK_NAME_CAMEL_CASE/edit', payload: {data, callback}});
  };

  handleRemove = (data: any) => {
    const { props: {dispatch} } = this;
    dispatch({type: 'BLOCK_NAME_CAMEL_CASE/remove', data});
  };

  handleSearch = (e: React.FormEvent) => {
    const {dispatch, form} = this.props;
    form.validateFields((err, fieldsValue) => {
      if (err) return;
      const filters = {
        ...fieldsValue,
        updatedAt: fieldsValue.updatedAt && fieldsValue.updatedAt.valueOf(),
      };

      this.setState({ formValues: filters });
      dispatch({type: 'BLOCK_NAME_CAMEL_CASE/fetch', filters});
    });
  };

  handleFormReset = () => {
    const {form, dispatch} = this.props;
    form.resetFields();
    this.setState({formValues: {}});
    dispatch({type: 'BLOCK_NAME_CAMEL_CASE/fetch', payload: {}});
  };

  handleModalVisible = (flag?: boolean) => {
    this.setState({addVisible: !!flag});
  };

  handleSelectRows = (rows: TableListItem[]) => {
    this.setState({selectedRows: rows});
  };

  handleTableChange = (
    pagination: Partial<TableListPagination>,
    filters: Record<keyof TableListItem, string[]>,
    sorter: SorterResult<TableListItem>,
  ) => {
    const {dispatch, form} = this.props;
    form.validateFields((err, fieldsValue) => {
      if (err) return;
      const filters = {
        ...fieldsValue,
        updatedAt: fieldsValue.updatedAt && fieldsValue.updatedAt.valueOf(),
      };

      this.setState({formValues: filters});
      dispatch({type: 'BLOCK_NAME_CAMEL_CASE/fetch', pagination, filters, sorter});
    });
  };

  renderSimpleForm() {
    const {form} = this.props;
    const {getFieldDecorator} = form;
    return (
      <Form onSubmit={this.handleSearch} layout="inline">
        <Row gutter={{md: 8, lg: 24, xl: 48}}>
          <Col md={6} sm={24}>
            <FormItem label="姓名">
              {getFieldDecorator('name')(<Input placeholder="请输入姓名"/>)}
            </FormItem>
          </Col>
          <Col md={6} sm={24}>
            <span>
              <Button type="primary" onClick={this.handleSearch}>
                查询
              </Button>
              <Button style={{marginLeft: 8}} onClick={this.handleFormReset}>
                重置
              </Button>
            </span>
          </Col>
        </Row>
      </Form>
    );
  }

  render() {
    const {BLOCK_NAME_CAMEL_CASE: {data}, loading, dispatch, } = this.props;
    const {selectedRows, addVisible, editVisible, selectedRecord } = this.state;

    const detailRender = (record: any) => {
      // this.handleGetConnector(record);
      return (
        <Row gutter={12} className={styles.loggingDetail}>
          <Col span={24}>
            <Card title={<a><Icon type="number"/>&nbsp;工作任务</a>}>
              {JSON.stringify(record['getSchemaInfo'])}
            </Card>
          </Col>
        </Row>
      );
    }
    return (
      <PageHeaderWrapper title={false}>
        <Card bordered={false}>
          <div className={styles.tableList}>
            <div className={styles.tableListForm}>{this.renderSimpleForm()}</div>
            <div className={styles.tableListOperator}>
              <Button icon="plus" type="primary" onClick={() => this.handleModalVisible(true)}>
                新建
              </Button>
            </div>
            <StandardTable
              columns={this.columns}
              loading={loading}
              data={data}
              rowKey="id"
              selectedRows={selectedRows}
              onSelectRow={this.handleSelectRows}
              onChange={this.handleTableChange}
              expandedRowRender={(record) => detailRender(record)}
            />
          </div>
        </Card>
        <AddView
          modalVisible={addVisible}
          handleAdd={this.handleAdd}
          handleModalVisible={this.handleModalVisible}
          dispatch={dispatch}
        />
        <EditView
          handleModalVisible={this.handleUpdateModalVisible}
          modalVisible={editVisible}
          messageType={selectedRecord}
          handleInvoke={this.handleEdit}
        />
      </PageHeaderWrapper>
    );
  }
}

export default Form.create<TableListProps>()(TableList);
